const express = require("express");
const app = express();
const cors = require('cors');
const mongoose = require("mongoose"); //引入mongoose


app.use(express.json());    //express要识别客户端传过来的json
app.use(cors()); //允许跨域 

//连接数据库
mongoose.connect("mongodb://localhost:27017/element-admin", {
  useNewUrlParser: true,
  useFindAndModify: true,
  useCreateIndex: true
});

//设计表结构
const Article = mongoose.model(
  "Article",
  new mongoose.Schema({
    title: { type: String },
    body: { type: String }
  })
);

//新增文章
app.post('/api/articles', async (req, res) => {
    const article = await Article.create(req.body);
    res.send(article);
});
//文章列表
app.get('/api/articles', async(req, res) => {
  const articles = await Article.find();
  res.send(articles);
});
//删除文章
app.delete('/api/articles/:id', async (req, res) => {
  await Article.findByIdAndDelete(req.params.id);
  res.send({
    status: true
  })
});
//获取文章
app.get('/api/articles/:id', async (req, res) => {
  const artice = await Article.findById(req.params.id);
  res.send(artice);
});
// 更新文章
app.put('/api/articles/:id', async (req, res) => {
  await Article.findByIdAndUpdate(req.params.id, req.body);
  res.send({
    status: true
  })
})

app.get("/", async (req, res) => {
  res.send("hello");
});
app.listen(3030, _ => {
  console.log("localhost:3030");
});
